/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.webapp.controller.management.organization;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.qinyeit.serviceapp.entity.Branch;
import com.qinyeit.serviceapp.entity.Department;
import com.qinyeit.serviceapp.entity.District;
import com.qinyeit.serviceapp.entity.enums.RoleType;
import com.qinyeit.serviceapp.entity.enums.Scope;
import com.qinyeit.serviceapp.entity.enums.State;
import com.qinyeit.serviceapp.entity.system.ManagementAccount;
import com.qinyeit.serviceapp.entity.system.ManagementPermission;
import com.qinyeit.serviceapp.entity.system.ManagementRole;
import com.qinyeit.serviceapp.entity.system.MerchantRolePermission;
import com.qinyeit.serviceapp.service.branchs.BranchDataServiceImpl;
import com.qinyeit.serviceapp.service.organization.BranchService;
import com.qinyeit.serviceapp.service.organization.DepartmentService;
import com.qinyeit.serviceapp.service.organization.DistrictService;
import com.qinyeit.serviceapp.service.system.ManagementPermissionService;
import com.qinyeit.serviceapp.service.system.ManagementRoleService;
import com.qinyeit.webapp.controller.management.BaseManagementController;
import com.qinyeit.webapp.utils.CurrentAccountUtils;
import com.qinyeit.webapp.utils.SearchableUtils;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.utils.JSONUtils;
import com.qinyetech.springstage.core.web.annotation.PageableDefaults;
import com.qinyetech.springstage.core.web.annotation.PermissionInfo;
import com.qinyetech.springstage.core.web.dto.ResponseResult;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * ClassName:positionsController <br/>
 * Function: position [角色] <br/>
 * date: 2018-11-20 13:19:32 <br/>
 *
 * @author liuwenjin
 * @version  1.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/management/organization/positions")
@PermissionInfo(parentName ="基础信息管理" ,parentOrder = 10,order = 10,code = "management_department:read",name ="角色",deleteAble = false)
public class PositionsController extends BaseManagementController{

    @Autowired
    private ManagementRoleService managementRoleService;
	@Autowired
	private DepartmentService departmentService;
	@Autowired
    private DistrictService districtService;
	@Autowired
    private ManagementPermissionService managementPermissionService;
	@Autowired
    private BranchDataServiceImpl branchDataService;
	@Autowired
    private BranchService branchService;
    //TODO include的字段,支持jsonPath
	private final String [] keys = {"id","name","code","description","deleteAble","attachDepartmentId","attachDistrictId","attachDataPermission",
	"attachDepartmentName","attachDistrictName","createAt","state","type","operatorName"};

    @RequiresPermissions("management_position:show")
    @PermissionInfo(code = "management_position:show",name ="查看",deleteAble = false)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")//默认按照id降序
    public ResponseResult<JSONObject> index(Searchable searchable){
        searchable.addSearchParam("code_ne","administrator");
        searchable = SearchableUtils.newSearchableWithMerchantFilter(searchable);
        Page<ManagementRole> managementRoles = managementRoleService.findAll(searchable);
        if (CollectionUtils.isNotEmpty(managementRoles.getContent())){
//            for (ManagementRole role : managementRoles) {
//                role.setAttachDepartmentName(departmentService.findById(role.getAttachDepartmentId()).getName());
//                role.setAttachDistrictName(districtService.findById(role.getAttachDistrictId()).getName());
//            }
        }
        QyMap map = QyMap.map("managementRoles",JSONUtils.include(managementRoles,new Class[]{State.class,RoleType.class}, keys));
//        initFormDate(map);

        //区域
        searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("parentId_ne",0);
        List<District> list=districtService.findWithSort(searchable);
        map.setv("districts",list);

        //状态
        map.setv("states", State.values());
        return ok("查询成功", map);
    }

    @GetMapping("/create")
    public ResponseResult<QyMap> _new(){
        QyMap map=QyMap.NEW();
        map.setv("position",JSONUtils.include(new ManagementRole(), keys));
        initFormDate(map);
        return ok("初始化成功", map);
    }

    @RequiresPermissions("management_position:create")
    @PermissionInfo(code = "management_position:create",name ="新增",deleteAble = false)
    @PostMapping("/create")
    public ResponseResult<String> create(@RequestBody JSONObject data, BindingResult bindingResult){
//        if(departmentService.exists(buildExists(null, "no", department.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        managementRoleService.saveData(data,CurrentAccountUtils.getAuthenticatedMerchantGroupID(),CurrentAccountUtils.getAuthenticatedEmployeeName());
        return ok("保存成功");
    }

    @GetMapping("/{id}")
    public ResponseResult<JSONObject> show(@ModelAttribute Department department){
        return ok("查询成功", JSONUtils.include(department, keys));
    }

    @GetMapping("/{id}/update")
    public ResponseResult<QyMap> edit(@ModelAttribute ManagementRole managementRole){
        QyMap map=QyMap.NEW();
//        log.info("编辑 ---- ： "+JSON.toJSONString(managementRole));
//        District district = districtService.findById(managementRole.getAttachDistrictId());
//        managementRole.setAttachDistrictName(district.getParentId()+"");
        map.setv("position",JSONUtils.include(managementRole, keys));


        //勾选的权限
        List<Object> mapList = managementRoleService.getPermission(managementRole.getId());
        map.setv("rolePermission",mapList);

        //门店后台权限
        map.setv("branchCheckBackPermissions", managementRoleService.getBranchPermissions(managementRole.getId(),Scope.BACK_END));
        //门店收银权限
        map.setv("branchCheckFrontPermissions",managementRoleService.getBranchPermissions(managementRole.getId(),Scope.FRONT_ENT));
        initFormDate(map);
        return ok("查询成功",map);
    }

    @RequiresPermissions("management_position:update")
    @PermissionInfo(code = "management_position:update",name ="修改",deleteAble = false)
    @PutMapping("/{id}/update")
    public ResponseResult<String> update(@RequestBody JSONObject data,BindingResult bindingResult){
//        if(departmentService.exists(buildExists(null, "no", department.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        managementRoleService.saveData(data,CurrentAccountUtils.getAuthenticatedMerchantGroupID(),CurrentAccountUtils.getAuthenticatedEmployeeName());
        return ok("更新成功", null);
    }

    @RequiresPermissions("management_position:destory")
    @PermissionInfo(code = "management_position:destory",name ="删除",deleteAble = false)
    @DeleteMapping("/{id}")
    public ResponseResult<String> destory(@PathVariable Long id){
        departmentService.logicDelete(id);
        return ok("删除成功", null);
    }


    /**
     * 部门修改状态
     *
     * @param id
     * @return
     */
    @RequiresPermissions("management_position:updateState")
    @PermissionInfo(code = "management_position:updateState",name ="修改状态",deleteAble = false)
    @GetMapping("/updateState")
    public ResponseResult<String> updateState(Long id){
        //有员工关联 不能停用
        ManagementRole managementRole = managementRoleService.findById(id);
        if(managementRole.getState()==State.NORMAL){
            managementRole.setState(State.DISABLED);
        }else {
            managementRole.setState(State.NORMAL);
        }
        managementRoleService.update(managementRole);
        return ok("操作成功", null);
    }



    @ModelAttribute
    public void preparedData(@PathVariable(value="id",required = false) String id,Model model){
        if(StringUtils.isNotBlank(id)){ //如果路径中有id参数则查询实体对象
            ManagementRole managementRole = managementRoleService.findById(Long.valueOf(id));
            model.addAttribute(managementRole);
        }
    }



    /**
     * 初始化表单数据
     * @param qyMap
     */
    private void initFormDate(QyMap qyMap){

        //区域
        List<District> list=districtService.getBuildTree(CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        qyMap.setv("districts",list);

        //状态
        qyMap.setv("states", State.values());

        //权限串
        List<ManagementPermission> permissionList = Lists.newArrayList();
        ManagementPermission permission = new ManagementPermission();
        permission.setName("总部后台");
        permission.setId(0L);
        permission.setParentId(0L);
        permission.setChildren(managementPermissionService.getPermission());
        permissionList.add(permission);
        qyMap.setv("permissions",JSONUtils.include(permissionList,"id","parentId","name","children"));

        //角色
        qyMap.setv("roleList", RoleType.values());

        //分店后台角色串
        List<Long> backPermissionChecked = qyMap.getList("branchCheckBackPermissions", Long.class);
        List<Long> frontPermissionChecked = qyMap.getList("branchCheckFrontPermissions", Long.class);

        List<Map<String,Object>> branchPermissions = Lists.newArrayList();
        Map<String,Object> map = Maps.newHashMap();
        map.put("id",0);
        map.put("name","分店后台");
        map.put("parentId",0L);
        map.put("children",branchDataService.getBranchPermissions("BACK_END", backPermissionChecked));
        branchPermissions.add(map);
        qyMap.setv("branchBackPermissions",branchPermissions);
//        backPermissionChecked.remove(0L);
        qyMap.setv("branchCheckBackPermissions", backPermissionChecked);


        //分店收银端角色串
        branchPermissions = Lists.newArrayList();
        map = Maps.newHashMap();
        map.put("id",0);
        map.put("name","收银权限");
        map.put("parentId",0L);
        map.put("children",branchDataService.getBranchPermissions("FRONT_ENT", frontPermissionChecked));
        branchPermissions.add(map);
        qyMap.setv("branchFrontPermissions",branchPermissions);
//        frontPermissionChecked.remove(0L);
        qyMap.setv("branchCheckFrontPermissions", frontPermissionChecked);


      /*  Searchable searchable = SearchableUtils.newSearchableWidthDeletedFilter();
        searchable.addSearchParam("parentId_eq",0L);
        List<ManagementPermission> permissions = managementPermissionService.findWithSort(searchable);
        if(CollectionUtils.isNotEmpty(permissionList)){
            qyMap.setv("ls_default_permissions",permissions.stream().map(x->x.getId()).collect(Collectors.toList()));
        }

        List<Long> ids = branchDataService.getbranchDefaultIds("BACK_END");
        qyMap.setv("fd_default_back_ids",ids);
        ids = branchDataService.getbranchDefaultIds("FRONT_ENT");
        qyMap.setv("fd_default_font_ids",ids);*/

    }

}